﻿using Arction.Wpf.BindableCharting;
using Arction.Wpf.BindableCharting.SeriesXY;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using WPF自由布局.Models;

namespace WPF自由布局.ViewModels
{
    public class SensorViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private Timer _timer;
        public string SensorName { get; set; }
        public ObservableCollection<SensorData> DataPoints { get; set; }

        private SeriesPointCollection _dataPoints; 


        public SeriesPointCollection DataPoints1
        {
            get => _dataPoints;
            set
            {
                if (_dataPoints != value)
                {
                    _dataPoints = value;
                    OnPropertyChanged(nameof(DataPoints1));
                }
            }
        }

        private SensorData _latestDataPoint;
        public SensorData LatestDataPoint
        {
            get { return _latestDataPoint; }
            set
            {
                _latestDataPoint = value;
                OnPropertyChanged(nameof(LatestDataPoint));
            }
        }

        public SensorViewModel(string sensorName)
        {
            SensorName = sensorName;
            DataPoints = new ObservableCollection<SensorData>();
            DataPoints1 = new SeriesPointCollection();
            _timer = new Timer(10); // 每2秒更新一次
            _timer.Elapsed += (s, e) => UpdateData();
            _timer.Start();
        }

        int j = 0;
        private void UpdateData()
        {
            var newData = new SensorData
            {
                SensorName = SensorName,
                Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Value = SensorName.Contains("温度")
                        ? new Random().Next(20, 30)  // 温度值
                        : new Random().Next(30, 100), // 湿度值
                Unit = SensorName.Contains("温度") ? "°C" : "%",
                Frequency = j++,
                Magnitude = SensorName.Contains("温度")
                        ? new Random().Next(0,10)  
                        : new Random().Next(15, 25),
                Speed = j,
            };

            App.Current.Dispatcher.Invoke(() =>
            {
                DataPoints.Add(newData);
                DataPoints1.Add(new SeriesPoint() { X = newData.Frequency, Y = newData.Magnitude });
                LatestDataPoint = newData; // 更新最新数据
                if (DataPoints.Count() > 100) { DataPoints.RemoveAndDispose(0);};
                if (DataPoints1.Count() > 100) { DataPoints.RemoveAndDispose(0); };
            });

        }


        protected void OnPropertyChanged(string propertyName = null) =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
